import 'dart:io';

import 'package:cloudapp/utils/parse_server_addr.dart';
import 'package:flutter/material.dart';
import 'package:get_ip/get_ip.dart';
import 'package:qrcode/qrcode.dart';

class QRCodeScan extends StatefulWidget {
  static const pageName = "/qrscan";
  @override
  State<StatefulWidget> createState() {
    return _QRCodeScan();
  }
}

class _QRCodeScan extends State<QRCodeScan> {
  var _captureController = QRCaptureController();

  @override
  void initState() {
    super.initState();

    _captureController.onCapture((data) {
      _captureController.pause();
      print('data: $data');
      try {
        var ipArray = parseServerAddr(data);
        getAddress().then((localAddr) {
          var dstAddr = diffIpAddrs(ipArray, localAddr);
          Navigator.of(context).pop(dstAddr);
          _captureController.resume();
        });
      } catch(e) {
        //
      }
    });
  }

  Future<InternetAddress> getAddress() async {
    String ipAddress = await GetIp.ipAddress;
    if(ipAddress == null) {
      throw GetLocalAddrFailed();
    }
    return InternetAddress(ipAddress);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('二维码扫描'),
        elevation: 0.0,
      ),
      body: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          QRCaptureView(controller: _captureController),
        ],
      ),
    );
  }
}
